import 'dart:io';
import 'package:aliyun_oss_flutter2/aliyun_oss_flutter2.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';
import '../api/api.dart';

class AliOssUtils {
  static const _endPoint = "oss-cn-chengdu.aliyuncs.com";
  static const _bucketName = "shengxp";
  static var _isInit = false;

  static upload(File file, Function(String) success, Function fail) async {
    var url = Api.HOST + "/v1/upload/token";
    work() async {
      var filename = const Uuid().v1() + ".jpg";

      Directory tempDir = await getTemporaryDirectory();
      var dd = Directory(tempDir.path + "/image");
      if (dd.existsSync()) {
        dd.deleteSync(recursive: true);
      }
      dd.createSync();

      String tempPath = tempDir.path + "/image/$filename";
      try {
        var compressFile = await FlutterImageCompress.compressAndGetFile(
            file.absolute.path, tempPath,
            minHeight: 800, minWidth: 800);

        var object = await OSSClient().putObject(OSSObjectPut.fromFile(
            file: compressFile!, key: "app/test/$filename"));
        if (object.url != null) {
          success(object.url!);
        } else {
          fail();
        }
      } catch (e) {
        fail();
      }
    }

    if (!_isInit) {
      Api.get(url, (data, response) {
        if (data != null) {
          //_isInit = true;
          var cred = data;
          OSSClient.init(
              endpoint: _endPoint,
              bucket: _bucketName,
              credentials: () async {
                return Credentials(
                    accessKeyId: cred["AccessKeyId"],
                    accessKeySecret: cred["AccessKeySecret"],
                    securityToken: cred["SecurityToken"],
                    expiration: DateTime.parse(cred["Expiration"]));
              });
          work();
        } else {
          fail();
        }
      });
    } else {
      work();
    }
  }
}